﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Reflection;

namespace TSL.Utility
{
    internal class AjaxRequestProcessor
    {
        private HttpContext context = null;
        internal AjaxRequestProcessor(HttpContext context)
        {
            this.context = context;
        }

        public void Run()
        {
            //获取空间命名和类名称
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(this.context.Request.FilePath);

            jQueryProcessor processor = new jQueryProcessor();
            processor.InitializeContext(ref this.context);

            this.context.Response.Expires = 0;
            this.context.Response.AddHeader("cache-control", "no-cache");
            this.context.Response.Charset = "UTF-8";

            //开始寻找程序集和程序结构
            Type type = Type.GetType(fileNameWithoutExtension);
            if (type == null)
            {
                processor.HandleException("本类型 '" + fileNameWithoutExtension + "' 进行数据提交失败.");
                return;
            }

            //如果非方法请求则生成JS
            string Mothodname = processor.GetMethodName();
            if (Mothodname == null)
            {
                this.context.Response.ContentType = "text/plain";
                processor.RenderClientScript(type);
                return;
            }

            MethodInfo method = type.GetMethod(Mothodname);
            if (method == null)
            {
                processor.HandleException("本类型未找到方法 '" + Mothodname + "' 进行数据提交失败.");
                return;
            }
            //执行反射后的方法
            processor.RegisterAjaxInvokeEvent(type, method);
        }
    }
}
